#include <iostream>
#define MAXSIZE 100000
#define Null -1
using namespace std;

struct Node{
	int data;
	int next;
}A[MAXSIZE];
void reversing_linked_list(int &Head,int k){
	int p = Head,rear = Head;
	while( p != Null){
		int q = A[p].next,cnt = 1,tmp = p;
		while( q!=Null && cnt<k ){
			int r = A[q].next;
			A[q].next = p;
			p = q; q = r; cnt++;
		}
		if( rear==Head ) Head = p;
		else{
			A[rear].next = p;
			rear = tmp;
		}
		A[rear].next = Null;
		p = q;
	}
}
int main(){
	freopen("in.txt","r",stdin);
	int Head,n,k;
	cin >> Head >> n >> k;
	for(int i=0; i<MAXSIZE; i++) A[i].next = Null;
	for(int i=0; i<n; i++){
		int a,b,c;
		cin >> a >> b >> c;
		A[a].data = b;
		A[a].next = c;
	}
	reversing_linked_list(Head,k);
	int p = Head;
	while( p != Null ){
		cout << p << " " << A[p].data << " " << A[p].next << endl;
		p = A[p].next;
	}
	return 0;
}
